package com.gf.common.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gf.common.Md5Encryption;
import com.gf.common.service.SMSService;

@Service
@Transactional
public class SMSServiceImpl implements SMSService {
	
	final private static String smsUserNameLx = "15003879831";
	final private static String smsPasswordLx = "xxzx67184946";
	
	final private static String sendSmsUrlLx = "http://www.lx198.com/sdk/send?";//乐信通信接口URL
	
//	static String smsSerUrl; //SMS中转服务URL,从配置文件获取
	
//	static Integer SMS_COMPANY;
	
	static String suffix = "【郑州质监】";//签名
	
	private static final Logger LOGGER = LoggerFactory.getLogger(SMSServiceImpl.class);
	
	/**
	 * 查询
	 */
	@Override
	public boolean sendSms(String smsSerUrl,Integer smsCompany,Long sendUserID, String phonenum, String content,
			String groupID, String systemName){
		boolean result = false;	
		if(smsCompany==2){
			System.out.println(content+suffix);
			return true;
		}
		if(smsCompany==0){
			result=sendSmsLx(smsSerUrl+"lexinsms.jsp", sendUserID, phonenum, content, groupID, systemName);
		}else{
			result=sendSmsHX(smsSerUrl+"sms.jsp", sendUserID, phonenum, content, groupID, systemName);
		}
		return result;
	}
	
	/**
	 * 乐信发信息接口
	 */
	@Override
	public boolean sendSmsLx(String smsSerUrl,Long sendUserID, String phonenum, String content,
			String groupID, String systemName) {
		boolean            result = false;	
	    HttpURLConnection  con    = null;
	    PrintWriter        out    = null;
	    BufferedReader     in     = null;
		try {
			StringBuilder sbPara = new StringBuilder();				
			
			sbPara.append("sendsmsurl=");
			sbPara.append(URLEncoder.encode(sendSmsUrlLx,"gb2312"));
			sbPara.append("&accName=");
			sbPara.append(URLEncoder.encode(smsUserNameLx,"gb2312"));
			sbPara.append("&accPwd=");
			sbPara.append(Md5Encryption.getInstance().getMd5String(smsPasswordLx));
			sbPara.append("&aimcodes=");
			sbPara.append(URLEncoder.encode(phonenum,"gb2312"));//phonenum,  0;签名未通过审核或者签名不正确!;0;0;0;0;0;
			sbPara.append("&content=");
			sbPara.append(URLEncoder.encode(content+suffix,"gb2312"));
			sbPara.append("&bizId="+createBizId());
			sbPara.append("&dataType=string");
			
			URL url = new URL(smsSerUrl);// 
			con = (HttpURLConnection)url.openConnection(); 
			
			con.setRequestMethod("POST");
			con.setDoInput(true);
			con.setDoOutput(true);
			
			out = new PrintWriter(con.getOutputStream());
			out.println(sbPara);
			out.flush();
			
			System.out.println(smsSerUrl+"  "+sbPara);
			//设置编码,否则中文乱码	
			in = new BufferedReader(new InputStreamReader(con.getInputStream(), "gb2312"));
	
			StringBuilder buff = new StringBuilder();
			String line;
			while ((line = in.readLine()) != null) {
				buff.append(line);
			}
			System.out.println(buff.toString());
			result=true;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if (out != null ) out.close();
			try {
				if (in != null) in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (con != null ) con.disconnect();
		}
		return result;
	}
	
	final private static String smsUserNameHx = "15003879831";
	final private static String smsPasswordHx = "xxzx67184946";
	
	final private static String sendSmsUrlHx = "http://www.lx198.com/sdk/send?";//华夏通信接口URL
	
	@Override
	public boolean sendSmsHX(String smsSerUrl,Long sendUserID,String phonenum, String content, String qfID, String systemName) {
		
	    boolean            result = false;	
	    HttpURLConnection  con    = null;
	    PrintWriter        out    = null;
	    BufferedReader     in     = null;
		try {
			StringBuilder sbPara = new StringBuilder();
			sbPara.append("sendsmsurl=");
			sbPara.append(URLEncoder.encode(sendSmsUrlHx,"gb2312"));
			sbPara.append("&username=");
			sbPara.append(URLEncoder.encode(smsUserNameHx,"gb2312"));
			sbPara.append("&password=");
			sbPara.append(URLEncoder.encode(smsPasswordHx,"gb2312"));
			sbPara.append("&destaddr=");
			sbPara.append(URLEncoder.encode(phonenum,"gb2312"));
			sbPara.append("&content=");
			sbPara.append(URLEncoder.encode(content+suffix,"gb2312"));
			
			URL url = new URL(smsSerUrl); 
			con = (HttpURLConnection)url.openConnection(); 
			
			con.setRequestMethod("POST");
			con.setDoInput(true);
			con.setDoOutput(true); 
			
			out = new PrintWriter(con.getOutputStream());
			out.println(sbPara);
			out.flush();
			
			// 设置编码,否则中文乱码	
			in = new BufferedReader(new InputStreamReader(con.getInputStream(), "gb2312"));
	
			StringBuilder buff = new StringBuilder();
			String line;
			while ((line = in.readLine()) != null) {
				buff.append(line);
			}
			System.out.println(buff);
			//获取短信发送返回的字符信息
			int bodyStart = buff.indexOf("<body>")+6;
		    int bodyEnd    = buff.indexOf("</body>");
		    String retInfo = buff.substring(bodyStart, bodyEnd);
		    LOGGER.info(retInfo);
		   
			//发送成功，响应为你的信息已经成功提交 x 条
			if(buff.indexOf("成功") >= 0){
				result = true;	
				LOGGER.info("短信发送成功结果:" + phonenum + "," + buff.toString());	
			}else{
				LOGGER.error("短信发送失败结果:" + phonenum + "," + buff.toString());	
			}//end of if
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}finally{
			if (out != null ) out.close();
			try {
				if (in != null) in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (con != null ) con.disconnect();
		}//end of finally
		
		return result;
	}
	
	public static  int curttNo;
	
	private final static String dataFormatString="yyMMddHHmmss";
	
	public synchronized static final String createBizId(){
		if(curttNo<999) {
			curttNo++;
		}else{
			curttNo=1;
		}
		String curttNoStr=String.valueOf(curttNo);
		while(curttNoStr.length()<3){;
			curttNoStr="0"+curttNoStr;
		}
		return new SimpleDateFormat(dataFormatString).format(new Date())+curttNoStr;
	}
}
